package com.lam.code.configuration.shiro;

import cn.hutool.core.util.StrUtil;
import com.lam.code.entity.User;
import com.lam.code.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

/**
 * @author lam
 * @description JWT鉴权验证域
 * @date 2019/12/22 22:44
 */
public class JWTRealm extends AuthorizingRealm {

    private UserService userService;

    public JWTRealm(UserService userService){
        this.userService = userService;
        //这里使用我们自定义的Matcher
        this.setCredentialsMatcher(new JWTCredentialsMatcher());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 更controller登录一样，也是获取用户的salt值，给到shiro，由shiro来调用matcher来做认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken auth) throws AuthenticationException {
        String token = (String)auth.getPrincipal();
        String userCode  = JWTUtil.getUserCode(token);

        if (StrUtil.isEmpty(userCode)) {
            throw new AuthenticationException("token invalid");
        }

        //使用缓存获取
        User user = userService.getUserInfoByCode(userCode);
        if(user == null) {
            throw new AuthenticationException("token过期，请重新登录");
        }

        return new SimpleAuthenticationInfo(user, JWTUtil.getSalt(userCode), this.getName());
    }

    /**
     * 在JWT Realm里面，因为没有存储角色信息，所以直接返回空就可以了
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        return new SimpleAuthorizationInfo();
    }

}
